package timesheet.controller;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.ModelAndView;

import timesheet.model.Badging;
import timesheet.model.Users;
import timesheet.repository.BadgingRepository;
import timesheet.repository.UserRepository;
import timesheet.web.ContextUtil;


@Controller
@Transactional
//don t forget the annotation @ transactionnal for keeping the connection db open
public class LoginController {

	@Autowired UserRepository userRepository;
	
	public static final String USERID_KEY = "UserId";  // Key in the HttpSession for the loggedin user.
	
	@Autowired BadgingRepository badgingRepository;
	
	@RequestMapping("/loginsubmit")
	public ModelAndView loginSubmit(@RequestParam("identifier") String pseudo,
			@RequestParam(value="password",required=false) String password,
			WebRequest request) {
		ModelAndView home = new ModelAndView("home");
		HttpSession session = ContextUtil.getHttpSession();
		if(!pseudo.isEmpty() && !password.isEmpty()){
			Users user = userRepository.getUserByUserName(pseudo);
			if(user != null && user.getPassword().equals(password)){
				// we register the id of the user in the session
				session.setAttribute(USERID_KEY, user.getId());
				session.setAttribute("LOGGED", true);
				session.setAttribute("ROLE", user.getRole());
				session.setAttribute("PSEUDO", user.getPseudo());
				if(badgingRepository.getLastBadgingTimeByUser(user) != null){
					Badging b = badgingRepository.getLastBadgingTimeByUser(user);
					if( b.getStart() != null && b.getStop() == null){
						session.setAttribute("STARTDAY", true);
						session.setAttribute("STOPDAY", false);
					}
					else{
						session.setAttribute("STARTDAY", false);
						session.setAttribute("STOPDAY", true);
					}
				}
				else{
					session.setAttribute("STARTDAY", false);
					session.setAttribute("STOPDAY", true);
				}
				Long idUser = (Long)ContextUtil.getHttpSession().getAttribute("UserId");
				return new ModelAndView("index");
			}
			else{
				if(user == null){
					String mes = "This user does not exist in our database";
					home.addObject("mesPass", mes);
				}
				else{
					String mes = "This user exist but the password is wrong";
					home.addObject("mesPass", mes);
				}
				return home;
			}
		}
		return home;
	}
	@RequestMapping("/logout")
	public ModelAndView logout(){
		ContextUtil.getHttpSession().removeAttribute(USERID_KEY);
		ContextUtil.getHttpSession().removeAttribute("LOGGED");
		ContextUtil.getHttpSession().removeAttribute("ROLE");
		return new ModelAndView("home");
	}
}
